package br.com.avaliacao;

import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.widget.EditText;

public class AvaliacaoParser
{
	private AvaliacaoCredito avaliacaoCredito;

	public AvaliacaoParser(AvaliacaoCredito avaliacaoCredito)
	{
		this.avaliacaoCredito = avaliacaoCredito;
	}

	private void lerAtributoAvaliacao(KXmlParser parser) throws XmlPullParserException, IOException
	{
		String name = parser.getName();
		String text = parser.nextText();
		if (name.equals("nome"))
		{
			EditText textNome = (EditText) avaliacaoCredito.findViewById(R.id.TextNome);
			textNome.setText(text);
		}
		if (name.equals("endereco"))
		{
			EditText textEndereco = (EditText) avaliacaoCredito.findViewById(R.id.EditTextEndenreco);
			textEndereco.setText(text);
		}
		if (name.equals("renda"))
		{
			EditText textRenda = (EditText) avaliacaoCredito.findViewById(R.id.EditTextRenda);
			textRenda.setText(text);
		}
		if (name.equals("situacao"))
		{
			EditText textSituacao = (EditText) avaliacaoCredito.findViewById(R.id.EditTextSituacao);
			textSituacao.setText(text);
		}
	}

	public void lerMensagem(HttpResponse response) throws IOException
	{
		KXmlParser parser = new KXmlParser();
		try
		{
			parser.setInput(new InputStreamReader(response.getEntity().getContent()));

			parser.next();
			parser.require(XmlPullParser.START_TAG, null, "soap:Envelope");
			parser.next();
			parser.require(XmlPullParser.START_TAG, null, "soap:Body");
			parser.next();
			parser.require(XmlPullParser.START_TAG, null, "ns2:avaliarResponse");
			parser.next();
			parser.require(XmlPullParser.START_TAG, null, "avaliacao");

			while (parser.nextTag() != XmlPullParser.END_TAG)
			{
				lerAtributoAvaliacao(parser);
			}

			parser.require(XmlPullParser.END_TAG, null, "avaliacao");
			parser.next();

			parser.require(XmlPullParser.END_TAG, null, "ns2:avaliarResponse");
			parser.next();

			parser.require(XmlPullParser.END_TAG, null, "soap:Body");
			parser.next();

			parser.require(XmlPullParser.END_TAG, null, "soap:Envelope");
			parser.next();
		}
		catch (XmlPullParserException e)
		{
			e.printStackTrace();
		}
	}
}
